package com.lly.songhigh.activity;

import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lly.songhigh.R;
import com.lly.songhigh.adapter.MusicFragmentAdapter;
import com.lly.songhigh.application.BaseApplication;
import com.lly.songhigh.constant.StringResouce;
import com.lly.songhigh.receiver.MyReceiver;
import com.lly.songhigh.service.MediaPlayerService;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.sso.UMSsoHandler;

import de.hdodenhof.circleimageview.CircleImageView;
import it.sephiroth.android.library.picasso.Picasso;

public class MainActivity extends BaseActivity implements View.OnClickListener {
    private TabLayout mainTablayout;
    private ImageView mainSearch;
    private Toolbar mainToolbar;
    private ViewPager mainViewpager;
    private DrawerLayout drawerLayout;
    private CheckBox drawerNight;
    private TextView drawerTime;
    private TextView drawerSet;
    private TextView drawerExit;
    private TextView drawerLogin;
    private TextView loading_name;
    private LinearLayout loading_layout;
    private CircleImageView loading_head_portrait;
    private long mExitTime;
    private boolean isColsed = true;
    public boolean isDestory = false;
    private MyReceiver receiver;
    private UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.login");
    public static final int requestCode = 100;
    public static final String ALARM_CLOCK_BROADCAST = "alarm_clock_broadcast";
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intent = new Intent(this, MediaPlayerService.class);
        startService(intent);
        BaseApplication.getInstance().addActivity(this);
        initView();
        receiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MyReceiver.NOTIFICATION_ITEM_BUTTON_LAST);
        intentFilter.addAction(MyReceiver.NOTIFICATION_ITEM_BUTTON_NEXT);
        intentFilter.addAction(MyReceiver.NOTIFICATION_ITEM_BUTTON_PLAY);
        intentFilter.addAction(MyReceiver.NOTIFICATION_ITEM_BUTTON_DELETE);
        registerReceiver(receiver, intentFilter);
    }

    /**
     * 初始化视图
     */
    private void initView() {
        mainTablayout = (TabLayout) findViewById(R.id.main_tablayout);
        mainSearch = (ImageView) findViewById(R.id.main_search);
        mainToolbar = (Toolbar) findViewById(R.id.main_toolbar);
        mainViewpager = (ViewPager) findViewById(R.id.main_viewpager);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerNight = (CheckBox) findViewById(R.id.drawer_night);
        drawerTime = (TextView) findViewById(R.id.drawer_time);
        drawerSet = (TextView) findViewById(R.id.drawer_set);
        drawerExit = (TextView) findViewById(R.id.drawer_exit);
        loading_name = (TextView) findViewById(R.id.loading_name);
        loading_layout = (LinearLayout) findViewById(R.id.loading_layout);
        loading_head_portrait = (CircleImageView) findViewById(R.id.loading_head_portrait);
        // 设置ViewPager并将ViewPager添加到TabLayout中
        MusicFragmentAdapter musicFragmentAdapter = new MusicFragmentAdapter(getSupportFragmentManager(), this);
        mainViewpager.setAdapter(musicFragmentAdapter);
        mainTablayout.setupWithViewPager(mainViewpager);
        drawerLogin = (TextView) findViewById(R.id.drawer_login);
        drawerLogin.setOnClickListener(this);


        IntentFilter filter = new IntentFilter();
        filter.addAction(ALARM_CLOCK_BROADCAST);
        registerReceiver(mAlarmReceiver, filter);
        // 添加自定义视图到TabLayout的Tab中
        for (int i = 0; i < mainTablayout.getTabCount(); i++) {
            TabLayout.Tab tab = mainTablayout.getTabAt(i);
            tab.setCustomView(musicFragmentAdapter.getTabView(i));
        }
        // 设置ToolBar
        mainToolbar = (Toolbar) findViewById(R.id.main_toolbar);
        setSupportActionBar(mainToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        // 设置抽屉
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, mainToolbar, R.string.open, R.string.close) {
            // 抽屉关闭监听
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                isColsed = true;
            }

            // 抽屉打开监听
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                isColsed = false;
            }
        };
        toggle.syncState();
        drawerLayout.setDrawerListener(toggle);
        // 设置TabLayout选中的颜色
        mainTablayout.setSelectedTabIndicatorColor(StringResouce.WHITE_COLOR);
        drawerNight.setOnClickListener(this);
        drawerTime.setOnClickListener(this);
        drawerSet.setOnClickListener(this);
        drawerExit.setOnClickListener(this);
        mainSearch.setOnClickListener(this);
    }

    // 监听手机上的BACK键
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 判断菜单是否关闭
            if (isColsed) {
                // 判断两次点击的时间间隔（默认设置为2秒）
                if ((System.currentTimeMillis() - mExitTime) > 2000) {
                    Toast.makeText(this, StringResouce.BACK_TO_TABLETOP, Toast.LENGTH_SHORT).show();
                    mExitTime = System.currentTimeMillis();
                } else {
                    Intent intent = new Intent(Intent.ACTION_MAIN);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addCategory(Intent.CATEGORY_HOME);
                    startActivity(intent);
                }
            } else {
                drawerLayout.closeDrawer(Gravity.LEFT);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        if (drawerLayout.isShown()) {
            drawerLayout.closeDrawer(Gravity.LEFT);
        }
        switch (v.getId()) {
            case R.id.drawer_login:
                Intent in = new Intent(this, LoadingActivity.class);
                startActivityForResult(in, requestCode);
                break;
            case R.id.drawer_night:
                changeViewMode();
                break;
            case R.id.drawer_time:
                showSleepDialog();
                break;
            case R.id.drawer_set:
                Intent settingsIntent = new Intent(MainActivity.this, SettingsActivity.class);
                startActivity(settingsIntent);
                break;
            case R.id.drawer_exit:
                BaseApplication.getInstance().exit();
                break;
            case R.id.main_search:
                Intent intent = new Intent(this, SearchActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    /**
     * 改变夜间模式
     */
    void changeViewMode() {
        boolean isNight = getApp().isNightMode();
        if (isNight)
            ChangeToDay();
        else
            ChangeToNight();

        recreate();
    }

    /**
     * 定时退出音乐播放器
     */
    public void showSleepDialog() {
        if (BaseApplication.mIsSleepClockSetting) {
            cancleSleepClock();
            Toast.makeText(getApplicationContext(), "已取消睡眠模式！",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        View view = View.inflate(this, R.layout.sleep_time, null);
        final Dialog dialog = new Dialog(this, R.style.Dialog);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(false);

        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
        dialogWindow.setAttributes(lp);
        dialog.show();
        final LinearLayout sleepLinearLayout = (LinearLayout) view.findViewById(R.id.sleepLinearLayout);
        final Button cancleBtn = (Button) view.findViewById(R.id.cancle_btn);
        final Button okBtn = (Button) view.findViewById(R.id.ok_btn);
        final EditText timeEt = (EditText) view.findViewById(R.id.time_et);
        View.OnClickListener listener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (v == cancleBtn) {
                    dialog.dismiss();
                } else if (v == okBtn) {
                    String timeS = timeEt.getText().toString();
                    if (TextUtils.isEmpty(timeS)
                            || Integer.parseInt(timeS) == 0) {
                        Toast.makeText(getApplicationContext(), "输入无效！",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                    setSleepClock(timeS);
                    dialog.dismiss();
                }
            }
        };

        cancleBtn.setOnClickListener(listener);
        okBtn.setOnClickListener(listener);
    }

    /**
     * 设置睡眠闹钟
     */
    private void setSleepClock(String timeS) {
        Intent intent = new Intent(ALARM_CLOCK_BROADCAST);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                MainActivity.this, 0, intent, 0);
        // 设置time时间之后退出程序
        int time = Integer.parseInt(timeS);
        long longTime = time * 60 * 1000L;
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.set(AlarmManager.RTC, System.currentTimeMillis() + longTime,
                pendingIntent);
        BaseApplication.mIsSleepClockSetting = true;
        Toast.makeText(getApplicationContext(), "将在" + timeS + "分钟后退出软件", Toast.LENGTH_SHORT)
                .show();
    }

    /**
     * 取消睡眠闹钟
     */
    private void cancleSleepClock() {
        Intent intent = new Intent(ALARM_CLOCK_BROADCAST);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                MainActivity.this, 0, intent, 0);
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.cancel(pendingIntent);
        BaseApplication.mIsSleepClockSetting = false;
    }

    private BroadcastReceiver mAlarmReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            stopService(intent);
            //退出程序
            BaseApplication.getInstance().exit();
        }

    };


    @Override
    protected void onDestroy() {
        unregisterReceiver(mAlarmReceiver);
        unregisterReceiver(receiver);
        stopService(intent);
        isDestory = true;
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent info) {
        super.onActivityResult(requestCode, resultCode, info);
        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode);
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, info);
        }
        if (requestCode == 100 && resultCode == 100) {
            String url = info.getStringExtra("profile_image_url");
            String textuer = info.getStringExtra("screen_name");
            loading_name.setText(textuer);
            Picasso.with(this).load(url).placeholder(R.mipmap.placeholder_avatar_138).error(R.mipmap.placeholder_avatar_138).into(loading_head_portrait);
            loading_layout.setVisibility(View.GONE);
            loading_name.setVisibility(View.VISIBLE);
            loading_head_portrait.setVisibility(View.VISIBLE);
        }

    }
}
